package com.sola.upload.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 
 * 
 * @Package: com.sola.upload.controller
 * @author: kangxiaohui
 * @date: 2017年8月12日 上午10:07:04
 *
 */
@Controller
public class UploadController {

	@RequestMapping("/toUpload")
	public String toUpload() {
		return "upload";
	}

	@RequestMapping("toUploadBatch")
	public String toUploadBatch() {
		return "uploadBatch";
	}

	@PostMapping("/upload")
	@ResponseBody
	public String upload(@RequestParam("pic") MultipartFile file) {
		String result = "上传成功";
		if (file.isEmpty()) {
			return "文件为空";
		} else {

			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(new File(file.getOriginalFilename())));
				bos.write(file.getBytes());
				bos.flush();
				bos.close();
			} catch (FileNotFoundException e) {
				result = "文件没有找打";
				e.printStackTrace();
			} catch (IOException e) {
				result = "读取文件错误文件";
				e.printStackTrace();
			}
			System.out.println(file);
		}
		return result;
	}

	@PostMapping("/upload/batch")
	@ResponseBody
	/**
	 * 页面为空也可以应射程对象,multipartFile.getSize() 必须要 > 0,才可以进行处理
	 * @param multipartFiles
	 * @param request
	 * @return
	 */
	public String batchUpload(@RequestParam("pic") List<MultipartFile> multipartFiles,HttpServletRequest request) {
		// public String batchUpload(@RequestParam("pic") MultipartFile[]
		// multipartFiles){
		String result = "上传成功";
		//List<MultipartFile> requestWay = ((MultipartHttpServletRequest)request).getFiles("pic");
		if (multipartFiles.size() > 0) {
			for (MultipartFile multipartFile : multipartFiles) {
				try {
					if(multipartFile.getSize() > 0){
						BufferedOutputStream bos = new BufferedOutputStream(
								new FileOutputStream(new File(multipartFile.getOriginalFilename())));
						bos.flush();
						bos.close();
					}
				} catch (FileNotFoundException e) {
					result = "文件没有找到";
					e.printStackTrace();
				} catch (IOException e) {
					result = "读取文件错误文件";
					e.printStackTrace();
				}
			}

		} else {
			return "文件为空";
		}
		return result;
	}

}
